package com.frejoys.store.controller;

import cn.hutool.crypto.SecureUtil;
import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.common.login.WxLoginDto;
import com.frejoys.common.enums.ESite;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.common.LoginVo;
import com.frejoys.service.EventPublisherService;
import com.frejoys.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "账户登录", description = "登录")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixStore)
@Authorization(Authority.Private)
public class MallLoginController {

    private final UserService userService;

    private final RedissonClient redissonClient;

    private final EventPublisherService eventPublisherService;


    @Authorization(Authority.Protected)
    @Operation(summary = "微信账户注册登录")
    @PostMapping("/wxLogin")
    public Result<LoginVo> wxLogin(@RequestBody @Validated WxLoginDto dto) {
        LoginVo vo = null;

        RLock lock = redissonClient.getLock(CacheKeyUtil.loginWxLockCacheKey(SecureUtil.md5(dto.getOpenidCode()), ESite.store.getValue()));

        if (lock.tryLock()) {
            try {

                vo = userService.wxLogin(dto, ESite.store.getValue(), RequestUtil.siteType());

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success(vo);
    }

}
